package br.com.android.financas.activities;

import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.joda.time.format.DateTimeFormat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import br.com.android.financas.R;
import br.com.android.financas.adapter.CategoriaSpinnerAdapter;
import br.com.android.financas.adapter.DataAdapter;
import br.com.android.financas.helper.HomeHelper;
import br.com.android.financas.model.Categoria;
import br.com.android.financas.model.Despesa;
import br.com.android.financas.repositorio.RepositorioCategoria;
import br.com.android.financas.repositorio.RepositorioDespesa;
import br.com.android.financas.repositorio.impl.RepositorioCategoriaImpl;
import br.com.android.financas.repositorio.impl.RepositorioDespesaImpl;
import br.com.android.financas.watcher.CurrencyWatcher;


public class HomeDespesa extends HomeHelper<Despesa> {

	private static final String CLICK_DESPESA_ID = "despesaId";
	private EditText campoValor,campoDescricao,campoParcelas;
	private Spinner campoCategoria,campoData,campoAte;
	private CheckBox permanente,parcelado;
	private TextView labelNovoValor, labelParcela,labelParcelado;
	private RepositorioDespesa repositorioDespesa;
	private RepositorioCategoria repositorioCategoria;
	private DataAdapter adapterAte;
	private Activity activity;
	private double tmpValor;
	private boolean jaParcelou=false;

	public HomeDespesa() {
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.despesa_screen);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		boolean novo=true;
		try {
			repositorioDespesa = new RepositorioDespesaImpl(this);
			repositorioCategoria = new RepositorioCategoriaImpl(this);

			Intent intent = getIntent();
			campoData = (Spinner) findViewById(R.despesa.data);
			campoAte = (Spinner) findViewById(R.despesa.ate);
			campoValor = (EditText) findViewById(R.despesa.valor);
			campoDescricao = (EditText) findViewById(R.despesa.descricao);
			campoCategoria = (Spinner) findViewById(R.despesa.categoria);
			permanente=(CheckBox) findViewById(R.despesa.permanente);
			parcelado=(CheckBox) findViewById(R.despesa.parcelado);
			campoParcelas=(EditText) findViewById(R.despesa.parcelas);
			labelNovoValor=(TextView) findViewById(R.despesa.label_novo_valor);
			labelParcela=(TextView) findViewById(R.despesa.label_parcelas);
			labelParcelado=(TextView) findViewById(R.despesa.label_parcelado);

			// ArrayAdapter<Cores> adapter = new ArrayAdapter<Cores>(this,
			// android.R.layout.simple_spinner_item, Cores.values());
			ArrayAdapter<Categoria> adapter = new CategoriaSpinnerAdapter(this,
					R.layout.categoria_item, repositorioCategoria.listar(),
					getString(R.string.selecione));
			campoCategoria.setAdapter(adapter);
			String data=(new DateTime()).toString("dd/MM/yyyy");
			getInstance().setData(new Date());
			if (intent.getExtras() != null
					&& intent.getExtras().get("id") != null) {
				novo=false;
				// get
				Integer id = (Integer) intent.getExtras().get("id");
				//despesa = repositorioDespesa.obterPorId((Integer) id);
				setId(id);

				campoValor.setText(NumberFormat.getCurrencyInstance().format(getInstance().getValor()));
				data= (new DateTime(getInstance().getData().getTime())).toString("dd/MM/yyyy");
				campoCategoria.setSelection(adapter.getPosition(getInstance().getCategoria()));
				campoDescricao.setText(getInstance().getDescricao());

				if(getInstance().isPai() || getInstance().getPai()!=null){
					TextView label=(TextView) findViewById(R.despesa.label_ate);
					campoAte.setVisibility(View.VISIBLE);
					label.setVisibility(View.VISIBLE);
					permanente.setChecked(true);

					DateTime at=new DateTime(getInstance().getUltimoFilho().getData().getTime());

					List<String> datasAte=new ArrayList<String>();
					datasAte.add(at.toString("dd/MM/yyyy"));
					adapterAte=new DataAdapter(this, android.R.layout.simple_spinner_item, datasAte);
					adapterAte.setMinimo(at);
					adapterAte.setDataSelecionada(at);

					campoAte.setAdapter(adapterAte);
				}

			}

			List<String> datas=new ArrayList<String>();

			datas.add(data);

			DataAdapter dataAdapter= new DataAdapter(this, android.R.layout.simple_spinner_item, datas);
			dataAdapter.setDataSelecionada(new DateTime(getInstance().getData().getTime()));
			campoData.setAdapter(dataAdapter);

			campoValor.setRawInputType(Configuration.KEYBOARD_12KEY);
			campoParcelas.setRawInputType(Configuration.KEYBOARD_12KEY);

			campoValor.addTextChangedListener(new CurrencyWatcher(campoValor));

			activity=this;
			permanente.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean check) {
					TextView label=(TextView) findViewById(R.despesa.label_ate);
					if(check){
						campoAte.setVisibility(View.VISIBLE);
						label.setVisibility(View.VISIBLE);
						DateTime at= DateTime.parse((String) campoData.getSelectedItem(),DateTimeFormat.forPattern("dd/MM/yyyy")).plusMonths(1) ;

						List<String> datasAte=new ArrayList<String>();
						datasAte.add(at.toString("dd/MM/yyyy"));
						adapterAte=new DataAdapter(activity, android.R.layout.simple_spinner_item, datasAte);
						adapterAte.setMinimo(at);
						adapterAte.setDataSelecionada(at);
						campoAte.setAdapter(adapterAte);
					}else{
						campoAte.setVisibility(View.GONE);
						label.setVisibility(View.GONE);
					}

				}
			});


			parcelado.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean check) {
					TextView labelPermanente=(TextView) findViewById(R.despesa.label_check);
					TextView labelAte=(TextView) findViewById(R.despesa.label_ate);

					if(check){
						permanente.setVisibility(View.GONE);
						labelPermanente.setVisibility(View.GONE);

						labelNovoValor.setVisibility(View.VISIBLE);
						campoParcelas.setVisibility(View.VISIBLE);
						labelParcela.setVisibility(View.VISIBLE);
						permanente.setChecked(true);
						labelAte.setVisibility(View.GONE);
						campoAte.setVisibility(View.GONE);

					}else{
						campoParcelas.setVisibility(View.GONE);
						labelParcela.setVisibility(View.GONE);
						labelNovoValor.setVisibility(View.GONE);
						permanente.setVisibility(View.VISIBLE);
						labelPermanente.setVisibility(View.VISIBLE);
						permanente.setChecked(false);
					}

				}
			});

//			campoParcelas.setOnFocusChangeListener(new OnFocusChangeListener() {
//				@Override
//				public void onFocusChange(View arg0, boolean out) {
//					if(!out){
//						atualizaParcelas(false);
//					}
//
//				}
//			});

			campoParcelas.addTextChangedListener(new TextWatcher() {

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					atualizaParcelas(false);

				}

				@Override
				public void beforeTextChanged(CharSequence s, int start, int count,
						int after) {
					// TODO Auto-generated method stub

				}

				@Override
				public void afterTextChanged(Editable s) {
					// TODO Auto-generated method stub

				}
			});

			campoValor.setOnFocusChangeListener(new OnFocusChangeListener() {

				@Override
				public void onFocusChange(View arg0, boolean out) {
					if(!out){
						try {
							tmpValor=NumberFormat.getCurrencyInstance().parse(campoValor.getText().toString()).doubleValue();
						} catch (ParseException e) {
						}
					}
				}
			});

			if(!novo){
				labelParcelado.setVisibility(View.GONE);
				parcelado.setVisibility(View.GONE);
			}

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void atualizaParcelas(boolean valor){
		int qtd=Integer.parseInt(campoParcelas.getText().toString());
		String data=(String) campoData.getSelectedItem();
		if(!data.isEmpty()){
			if(campoValor.getText().length()>0){

				DateTime at = DateTime.parse(data,DateTimeFormat.forPattern("dd/MM/yyyy")).plusMonths(qtd-1);
				List<String> datasAte=new ArrayList<String>();
				datasAte.add(at.toString("dd/MM/yyyy"));
				adapterAte=new DataAdapter(activity, android.R.layout.simple_spinner_item, datasAte);
				adapterAte.setMinimo(at);
				adapterAte.setDataSelecionada(at);
				campoAte.setAdapter(adapterAte);
			}
		}
		if(!jaParcelou){
			double novoValor=tmpValor/qtd;

			labelNovoValor.setText(NumberFormat.getCurrencyInstance().format(novoValor));
			if(valor)
				campoValor.setText(NumberFormat.getCurrencyInstance().format(novoValor));

			jaParcelou=true;
		}else{

			try {
				double novoValor=NumberFormat.getCurrencyInstance().parse(campoValor.getText().toString()).doubleValue();
				if(novoValor!=(tmpValor/qtd)){
					labelNovoValor.setText(NumberFormat.getCurrencyInstance().format(tmpValor/qtd));
					if(valor)
						campoValor.setText(NumberFormat.getCurrencyInstance().format(tmpValor/qtd));

					jaParcelou=true;
				}
			} catch (ParseException e) {
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.home_despesa, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in action bar clicked; go home
			/*intent = new Intent(this, Home.class);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);*/
			getIntent().putExtra("changed", false);
			setResult(RESULT_CANCELED, getIntent());
			finish();
			return true;
		case R.id.menu_save:

			try {
				if(parcelado.isChecked())
					atualizaParcelas(true);


				if(!isValid()){
					Toast.makeText(this, R.string.required_fields, Toast.LENGTH_LONG).show();
					return false;
				}


				if (getInstance().getId() == null) {
					return salva();
				} else {
					atualizar();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}

			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private boolean salva() throws SQLException {

		if(permanente.isChecked()){
			DateTime ini = new DateTime(getInstance().getData().getTime());
			DateTime fim = DateTime.parse(campoAte.getSelectedItem().toString(),DateTimeFormat.forPattern("dd/MM/yyyy"));

			Period p = new Period(ini, fim, PeriodType.months().withDaysRemoved());
			int qtd = p.getMonths();
			qtd=qtd==0? (ini.isEqual(fim)?1:0):qtd+1;
			if (qtd > 0 ) {

				String descricao=getInstance().getDescricao().trim();
				getInstance().setDescricao(descricao + " 1/" + qtd);
				repositorioDespesa.inserir(getInstance());

				double valor = getInstance().getValor();
				Categoria categoria = getInstance().getCategoria();

				for (int i = 1; i < qtd; i++) {
					Despesa d = new Despesa();
					d.setCategoria(categoria);
					d.setDescricao(descricao + " " + (i + 1) + "/" + qtd);
					d.setValor(valor);
					d.setData(ini.plusMonths(i).toDate());
					d.setPai(getInstance());

					repositorioDespesa.inserir(d);
				}
			}
		}else{
			repositorioDespesa.inserir(getInstance());
		}

		getIntent().putExtra("changed", true);
		setResult(RESULT_OK, getIntent());
		finish();
		return true;
	}

	private void atualizar(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		LayoutInflater factory = LayoutInflater.from(this);
	    View layout = factory.inflate(R.layout.apagar_despesa, null);
		final CheckBox todas = (CheckBox) layout.findViewById(R.apagar.todasGrupo);
		final CheckBox frente = (CheckBox) layout.findViewById(R.apagar.paraFrente);


		if( ( getInstance().isPai() || getInstance().getPai()!=null)){

			todas.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean check) {
					if(check){
						frente.setVisibility(View.INVISIBLE);
					}else
						frente.setVisibility(View.VISIBLE);
				}
			});

			builder.setView(layout);
			builder.setTitle(R.string.atualizar_movimentacoes);
		}else{
			builder.setTitle(R.string.atualizar_movimentacao);
			builder.setMessage(R.string.confirmar_atualizacao);
		}


		builder.setCancelable(false);
		builder.setPositiveButton(R.string.sim,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						try {
							if (getInstance() != null){
								DateTime dataUltima=null;
								if(todas.isChecked()){
									dataUltima=new DateTime(getInstance().getUltimoFilho().getData().getTime());
									repositorioDespesa.atualizarGrupo(getInstance());
								}else if(frente.isChecked())
								{
									dataUltima=new DateTime(getInstance().getUltimoFilho().getData().getTime());
									repositorioDespesa.atualizarGrupo(getInstance(),getInstance().getData());
								}else{
									repositorioDespesa.atualizar(getInstance());
								}

								if(dataUltima!=null){
									DateTime at = DateTime.parse(campoAte.getSelectedItem().toString(),DateTimeFormat.forPattern("dd/MM/yyyy"));

									if(dataUltima.isBefore(at)){
										Period p = new Period(dataUltima, at, PeriodType.months().withDaysRemoved());
										int qtd = p.getMonths();
										qtd=qtd==0?1:qtd;
										int a= getInstance().isPai()?getInstance().getFilhos().size():getInstance().getPai().getFilhos().size();
										qtd+=a;
										if (qtd > 0 ) {

											String descricao=getInstance().getDescricao().trim();
											descricao=descricao.replaceAll("\\d+\\/\\d+", "");
											descricao.trim();
											Despesa pai=getInstance().isPai()?getInstance():getInstance().getPai();
											double valor = getInstance().getValor();
											Categoria categoria = getInstance().getCategoria();
											DateTime ini=new DateTime(getInstance().getUltimoFilho().getData().getTime());
											int b=1;
											for (int i = a; i < qtd; i++) {
												Despesa d = new Despesa();
												d.setCategoria(categoria);
												d.setDescricao(descricao + " " + (i + 1) + "/" + qtd);
												d.setValor(valor);
												d.setData(ini.plusMonths(b).toDate());
												d.setPai(pai);
												b++;
												repositorioDespesa.inserir(d);
											}

											repositorioDespesa.atualizarDescricao(pai);
										}
									}
								}
							}
							Toast.makeText(activity,R.string.atualizado_sucesso, Toast.LENGTH_LONG).show();
							getIntent().putExtra("changed", true);
							setResult(RESULT_OK, getIntent());
							finish();
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});
		builder.setNegativeButton(R.string.nao,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();


	}

	public static void callMe(Activity c, Integer id) {
		//Intent intent = new Intent(c, HomeDespesa.class);
		//intent.putExtra(CLICK_DESPESA_ID, id);
		c.getIntent().setClass(c, HomeDespesa.class);
		c.getIntent().putExtra(CLICK_DESPESA_ID, id);
		c.startActivityForResult(c.getIntent(), 1);
	}

}
